package com.yunshang.shoppingmall.shopping.OrderController;


import com.alibaba.fastjson.JSON;
import com.yunshang.shoppingmall.Methods.FinaceMethods;
import com.yunshang.shoppingmall.common.HttpRequest;
import com.yunshang.shoppingmall.common.JacksonHelper;
import com.yunshang.shoppingmall.common.weixin.WeChat;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.entity.pojo.TaskRequest;
import com.yunshang.shoppingmall.entity.pojo.TaskResponse;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;


@RequestMapping("/wap")
@Controller
public class orderListController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderListService orderListService;
    @Autowired
    AddressService addressService;
    @Autowired
    ConfigService configService;
    @Autowired
    LogisticsService logisticsService;
    @Autowired
    OrderAddressService orderAddressService;
    @Autowired
    CartService cartService;
    @Autowired
    FinaceService finaceService;
    @Autowired
    FinaceTotalService finaceTotalService;
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    UserNoAchievementService userNoAchievementService;
    @Autowired
    OrderDetailsService orderDetailsService;

    private final static String ENCODE = "GBK";
    @ResponseBody
    @RequestMapping("/getOrderList")
    //会员中心订单列表
    public ModelAndView getOrderList(HttpServletRequest request,String orderStatus) {

        String htmlName="shoppingApi/order/orderList";
        if(orderStatus.equals("701")){
            htmlName="shoppingApi/order/orderList701";
        }
        if(orderStatus.equals("702")){
            htmlName="shoppingApi/order/orderList702";
        }
        if(orderStatus.equals("703")){
            htmlName="shoppingApi/order/orderList703";
        }
        if(orderStatus.equals("704")){
            htmlName="shoppingApi/order/orderList704";
        }
        ModelAndView modelAndView=new ModelAndView(htmlName);
        Map<String, Object> map=new HashMap<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        if(orderStatus==""||orderStatus=="null")
        {
            orderStatus="0";
        }
        List<OrderList> orderList=orderListService.selectOrderList(memberUserId,Integer.parseInt(orderStatus));
         if(orderList!=null&&orderList.size()>0){
             for (OrderList orderList1: orderList) {
                 List<String> list=new ArrayList<>();
                 List<String> listType=new ArrayList<>();
                 List<LogInfo> logInfos=new ArrayList<>();
                 String logStrs=orderList1.getLogisticalNo()==null?"":orderList1.getLogisticalNo();
                 for (String str: logStrs.split(",")) {
                     if(str!=null&&!str.equals("")){
                         list.add(str);
                         String type=logisticsService.getLogType(str);
                         //System.out.println("------"+type);
                         listType.add(type);

                         LogInfo logInfo=new LogInfo();
                         logInfo.setType(type);
                         logInfo.setNo(str);
                         logInfos.add(logInfo);
                     }
                 }
                 orderList1.setLogNoList(list);
                 orderList1.setLogType(listType);
                 orderList1.setLogInfoList(logInfos);
             }
         }
        orderList=setOrderList(orderList);
        orderList=paging(orderList,1,5);
        map.put("list",orderList);
        modelAndView.addObject("orderList",map);
        return  modelAndView;
    }


    public List<OrderList> paging(List<OrderList> list,Integer page,Integer pageSize)
    {
        int size = list.size();
        int pageCount=size/pageSize;
        int fromIndex = pageSize * (page - 1);
        int toIndex = fromIndex + pageSize;
        if (toIndex >= size) {
            toIndex = size;
        }
        if(page>pageCount+1){
            fromIndex=0;
            toIndex=0;
        }
        return list.subList(fromIndex, toIndex);
    }

    public List<OrderList> setOrderList(List<OrderList> orderLists)
    {
        for (int i = 0; i < orderLists.size(); i++) {
            int count=0;
            for (int j = 0; j < orderLists.get(i).getOrderDetailsProducts().size(); j++) {
                count +=orderLists.get(i).getOrderDetailsProducts().get(j).getProductCount();
            }
            orderLists.get(i).setCount(count);
        }
        return orderLists;
    }
    @ResponseBody
    @RequestMapping(value = "/getOrderListPage",method = RequestMethod.POST)
    //会员中心订单列表
    public Map<String,Object> getOrderListPage(HttpServletRequest request) {
        List<OrderList> orderLists=new ArrayList<>();
        String page = request.getParameter("page");
        String orderStatus = request.getParameter("orderStatus");
        if(orderStatus==""||orderStatus=="null")
        {
            orderStatus="0";
        }
        int pageSize=5;
        if (page!=null&&page!="")
        {
            if(Integer.parseInt(page)<=1)
            {
                page="1";
            }
        }
        else
        {
            page="1";
        }
        Map<String, Object> map=new HashMap<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        List<OrderList> orderList=orderListService.selectOrderList(memberUserId,Integer.parseInt(orderStatus));
        orderList=setOrderList(orderList);
        orderList=paging(orderList,Integer.parseInt(page),5);
        System.out.println("数据"+orderList.size());
        map.put("orderList",orderList);
         return map;
    }


    //订单详情
    @ResponseBody
    @RequestMapping("/getOrderDetails")
    public ModelAndView getOrderDetails(HttpServletRequest request)  {
        String htmlName="shoppingApi/user/loginbypassword";
        String orderNo = request.getParameter("orderNo");
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            htmlName="shoppingApi/order/orderDetails";
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }else {
            ModelAndView modelAndView=new ModelAndView(htmlName);
            return  modelAndView;
        }
        ModelAndView modelAndView=new ModelAndView(htmlName);
        Map<String, Object> map=new HashMap<>();
        OrderList orderList=orderListService.selectOrder(orderNo);//查询订单详情
//        System.out.println("orderList:"+orderList.toString());
//        System.out.println("getOrderDetailsProducts:"+orderList.getOrderDetailsProducts().toString());
        Order order=orderService.selectByNo(orderNo);
        if(order!=null){
            String orderStatus=order.getOrderStatus()==null?"0":order.getOrderStatus();
            String orderMessage=order.getOrderMessage()==null?"0":order.getOrderMessage();
            if((orderStatus.equals("701")||orderStatus.equals("706"))&&orderMessage.equals("1")){
                try {
                  Boolean bool=  deal(order);
                  if(bool){
                      order.setOrderStatus("702");
                  }
                }catch (Exception e){

                }

            }
        }
        List<OrderDetailsProduct> orderDetailsProductList=orderDetailsService.selectOrderDetailsProductByOrderNo(orderNo);
        int isMoreAddress=0;
        if(orderDetailsProductList!=null&&orderDetailsProductList.size()>0){
            for (OrderDetailsProduct orderDetailsProduct:orderDetailsProductList) {
                int isMoreAddressTemp=orderDetailsProduct.getIsMoreAddress()==null?0:orderDetailsProduct.getIsMoreAddress();
                if(isMoreAddressTemp==1){
                    isMoreAddress=isMoreAddressTemp;
                }
            }
        }
        OrderAddress orderAddress=orderAddressService.selectByPrimaryKey(order.getAddressId());
        //Address address=addressService.selectDefault(1,memberUserId);
        //address.setPhone(address.getPhone());//.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));//隐藏手机号中间4位
        Config userConfig= configService.selectByPrimaryKey(1);//货币名称显示
        System.out.println("isMoreAddress:"+isMoreAddress);
        map.put("WebConfig",userConfig);
        map.put("orderDetails",orderList);
        map.put("order",order);
        map.put("address",orderAddress);
        map.put("isMoreAddress",isMoreAddress);
        modelAndView.addObject("orderDetails",map);
        return  modelAndView;
    }


    public boolean deal(Order order) throws Exception {
        double getRealPay=order.getRealPay()==null?0:order.getRealPay();
        double getFreight=order.getFreight()==null?0:order.getFreight().doubleValue();
        double getInter=order.getInter()==null?0:order.getInter().doubleValue();
        double getCostInter=order.getCostInter()==null?0:order.getCostInter().doubleValue();
boolean orderbool=false;
        String cash1=(getRealPay+getFreight-getInter-getCostInter)+"";
        boolean bools1= WeChat.getOrder(order.getOrderNo(),cash1);
        if(bools1){
            orderbool=true;
            String orderNo=order.getOrderNo();
            Config config=configService.selectByPrimaryKey(1);
            String userNoId1="";
            if(order.getUserId()!=null){
                userNoId1=order.getUserId().toString();
            }else {
                Cart cart=cartService.selectByOrderNo(orderNo).get(0);
                if(cart!=null){
                    userNoId1=cart.getUserId().toString();
                }
            }

            UserNo userNoSS=sysUserNoService.selectByPrimaryKey(Integer.parseInt(userNoId1));
            String cash=cash1;
            double balance=0;
            int userNoId=Integer.parseInt(userNoId1);
            FinaceTotal finaceTotal=finaceTotalService.selectFinaceBalaceAll(userNoId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String date1 = sdf.format(date);


            UserNo userNo1 = userNoSS;

            int memberUserId = 0,memberLevel = 0,ids = 0,userNoReCommendId=0;//推荐人id
            UserRank  userRank=null;
            UserRank recommendUserRank=null;//推荐人的等级
            UserNo recommendUserNo=null;
            int recommendRankId=0;
            double recommendCommission=0.00;
            if (userNo1 != null) {
                memberUserId = userNo1.getId();//用户编号ID
                memberLevel = userNo1.getRank();
                userNoReCommendId=userNo1.getRecommend();
                userRank=userRankService.selectByPrimaryKey(memberLevel);//用户等级
                recommendUserNo=sysUserNoService.selectByPrimaryKey(userNoReCommendId);
                if(recommendUserNo!=null){
                    recommendRankId=recommendUserNo.getRank();
                    recommendUserRank=userRankService.selectByPrimaryKey(recommendRankId);
                    if(recommendUserRank!=null){
                        recommendCommission=recommendUserRank.getCommission();
                    }
                }
            }
            //推荐人积分
            double recommendBalance=0.00;
            int recommendFId=0;
            FinaceTotal f=new FinaceTotal();
            f.setfType("1");
            f.setUserId(userNoReCommendId);
            FinaceTotal recommendFinaceTotal = FinaceMethods.selectFinaceBalace(f); //推荐人积分
            if(recommendFinaceTotal!=null){
                recommendFId=recommendFinaceTotal.getfId();
                recommendBalance=recommendFinaceTotal.getBalance();
            }


            Boolean bools=true;
            double amount;

            Boolean strResult = cash.matches("-?[0-9]+.*[0-9]*");
            System.out.println("strResult"+strResult);
            if(strResult==false){
                amount=0;
            }else {
                amount=Double.parseDouble(cash);
            }

            if(amount>0){//现金支付是否大于0
                FinaceToData finaceToData = new FinaceToData();
                finaceToData.setUserId(userNoId);//用户编号Id
                finaceToData.setFinaceType("777");
                finaceToData.setRemark("充值"+orderNo);
                finaceToData.setClassify(1);
                finaceToData.setFinaceTime(Timestamp.valueOf(date1));//时间
                finaceToData.setAmount(BigDecimal.valueOf(amount));//积分
                //用户积分的余额
                finaceToData.setBalance(BigDecimal.valueOf(finaceTotal.getBalance1() + amount));
                finaceToData.setOpratorUId(userNoId);
                int res = finaceService.insertFinaceData(finaceToData);
                if(res<=0){
                    bools=false;
                    System.out.println("Classify1");
                    Logger logger= LoggerFactory.getLogger("Classify1"+orderNo);
                    //throw new RuntimeException();
                }
            }
            BigDecimal amount1;
            if(order.getRealPay()!=null&&order.getFreight()!=null){
                Boolean strResult1 = order.getRealPay().toString().matches("-?[0-9]+.*[0-9]*");
                Boolean strResult2 = order.getFreight().toString().matches("-?[0-9]+.*[0-9]*");
                if(strResult1==false||strResult2==false){
                    amount1=BigDecimal.valueOf(0);
                }else {
                    amount1=BigDecimal.valueOf(order.getRealPay()).add(order.getFreight());
                }
            }else {
                amount1=BigDecimal.valueOf(0);
            }
            if(amount1.doubleValue()>0){//实际支付总金额
                System.out.println("Classify1a");
                FinaceToData finaceToData1 = new FinaceToData();
                finaceToData1.setUserId(userNoId);//用户编号Id
                finaceToData1.setFinaceType("111");
                finaceToData1.setRemark("支出"+orderNo);
                finaceToData1.setClassify(1);
                finaceToData1.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal costinter=order.getCostInter()==null?BigDecimal.valueOf(0):order.getCostInter();
                BigDecimal am=amount1.subtract(costinter);
                finaceToData1.setAmount(new BigDecimal(-am.doubleValue()));//积分
                balance=(finaceTotal.getBalance1()+amount+costinter.doubleValue())-amount1.doubleValue();
                finaceToData1.setBalance(BigDecimal.valueOf(balance));
                finaceToData1.setOpratorUId(userNoId);
                int res1 = finaceService.insertFinaceData(finaceToData1);
                if(res1<=0){
                    bools=false;
                    System.out.println("Classify1b");
                    Logger logger= LoggerFactory.getLogger("Classify1b"+orderNo);
                    //throw new RuntimeException();
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(balance);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("1");
                    int cosRow;
                    if(finaceTotal.getfId1()>0){
                        finaceTotal4.setfId(finaceTotal.getfId1());
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        bools=false;
                        System.out.println("Classify1c");
                        Logger logger= LoggerFactory.getLogger("Classify1c"+orderNo);
                        //消费积分扣除有误，支付失败!
                        //throw new RuntimeException();
                    }
                }
            }
            if(order.getCostInter()!=null){//订单实际支付使用的消费积分
                if(order.getCostInter().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(4);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCostInter();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance4()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //消费积分扣除有误
                        bools=false;
                        System.out.println("Classify4");
                        Logger logger= LoggerFactory.getLogger("Classify4"+orderNo);
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId4());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance4()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("4");
                        int cosRow;
                        if(finaceTotal.getfId4()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify4a");
                            Logger logger= LoggerFactory.getLogger("Classify4a"+orderNo);
                            //消费积分扣除有误，支付失败!
                            //throw new RuntimeException();
                        }
                    }
                }
            }
            if(order.getCoupon()!=null){
                if(order.getCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(2);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance2()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //购物券扣除有误
                        bools=false;
                        System.out.println("Classify2b");
                        Logger logger= LoggerFactory.getLogger("Classify2b"+orderNo);
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId2());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance2()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("2");
                        int cosRow;
                        if(finaceTotal.getfId2()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify2c");
                            Logger logger= LoggerFactory.getLogger("Classify2c"+orderNo);
                            //消费积分扣除有误，支付失败!
                            //throw new RuntimeException();
                        }
                    }
                }
            }
            if(order.getCashCoupon()!=null){
                if(order.getCashCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(3);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCashCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance3()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        bools=false;
                        System.out.println("Classify3a");
                        Logger logger= LoggerFactory.getLogger("Classify3a"+orderNo);
                        //代金券扣除有误
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId3());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance3()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("3");
                        int cosRow;
                        if(finaceTotal.getfId3()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify3b");
                            Logger logger= LoggerFactory.getLogger("Classify3b"+orderNo);
                        }
                    }
                }
            }
            //返还折扣券保存到数据库返finance3_table
            Integer cashCouponMul = 0;
            String financeName = "";
            if(config!=null){
                if(config.getCashcouponmul()!=null){
                    cashCouponMul = config.getCashcouponmul();//返折扣券的倍数 ---2倍
                }
                if(config.getFinacename3()!=""||config.getCashcouponmul()!=null){
                    financeName = config.getFinacename3();//返回----折扣券的名称
                }
            }
            if(cashCouponMul>0){
                int resf = FinaceMethods.insertFinaceU(3, BigDecimal.valueOf(order.getBackCashcoupon() * cashCouponMul), userNoId, order.getOrderNo() + "返" + financeName, userNoId, 999);
            }
            //更新会员等级
            if (memberLevel == 19) {
                userNo1.setRank(16);
                int resu = sysUserNoService.updateByPrimaryKeySelective(userNo1);
                if (resu <= 0) {
                    //日志or数据库
                    bools=false;
                    System.out.println("bbbb");
                    Logger logger= LoggerFactory.getLogger("bbbb"+orderNo);
                    //throw new RuntimeException();
                }
            }
            order.setOrderStatus("702");
            order.setPayStatus("1");
            order.setPayTime(new Date());

            //添加记录运营成本到用户业绩表
            double opratorCost=0.00;//订单运营成本
            UserNoAchievement userNoAchievement=new UserNoAchievement();
            userNoAchievement.setOpratorCostSign("0");//为结算的业绩标志
            userNoAchievement.setUserNoId(memberUserId);
            userNoAchievement.setPayTime(new Timestamp(order.getpOrderTime().getTime()));
            if(order!=null&&order.getOpratorCost()!=null){
                order.getOpratorCost().doubleValue();
            }
            userNoAchievement.setOrderId(order.getOrderId());
            userNoAchievement.setOrderOpratorCost(opratorCost);
            if(opratorCost>0) {
                //int achievementRow = userNoAchievementService.insertSelective(userNoAchievement);
                //添加记录运营成本到用户业绩表
            }
            //分享赚
            if(userNoReCommendId<=0){//没有推荐人默认为零散会员编号id为62240
                userNoReCommendId=62240;
            }
            if(userNoReCommendId>0){//是否有推荐人
                double orderProfit=order.getOrderProfit();//订单利润
                double shareEaring=0.00;
                System.out.println("recommendCommission:"+recommendCommission);
                System.out.println(userRank.toString()+"----");
                if(recommendCommission-userRank.getCommission()>0){
                    shareEaring=orderProfit*(recommendCommission-userRank.getCommission())/100;
                }
                if(shareEaring>0){
                    FinaceToData finaceToDataRe = new FinaceToData();
                    finaceToDataRe.setUserId(userNoReCommendId);//推荐人用户编号Id
                    finaceToDataRe.setFinaceType("888");
                    finaceToDataRe.setRemark("分享赚"+orderNo);
                    finaceToDataRe.setClassify(1);
                    finaceToDataRe.setFinaceTime(Timestamp.valueOf(date1));//时间
                    finaceToDataRe.setAmount(new BigDecimal(shareEaring));//积分
                    finaceToDataRe.setBalance(new BigDecimal(shareEaring+recommendBalance));
                    finaceToDataRe.setOpratorUId(userNoReCommendId);
                    int row1 = finaceService.insertFinaceData(finaceToDataRe);
                    if(row1<=0){
                        bools=false;
                        System.out.println("12");
                        Logger logger= LoggerFactory.getLogger("12"+orderNo);
                        //throw new RuntimeException();
                    }
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userNoReCommendId);
                    finaceTotal4.setBalance(recommendBalance+shareEaring);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoReCommendId);
                    finaceTotal4.setUserId(userNoReCommendId);
                    finaceTotal4.setfType("1");
                    int recommendF;
                    if(recommendFId>0){
                        finaceTotal4.setfId(recommendFId);
                        recommendF=finaceTotalService.updateByPrimaryKey(finaceTotal4);
                    }else {
                        recommendF=finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if(recommendF<=0){
                        bools=false;
                        System.out.println("122");
                        Logger logger= LoggerFactory.getLogger("122"+orderNo);
                        //throw new RuntimeException();
                    }
                }

            }
            //分享赚

            orderService.activity(order,memberUserId+"",userRank.getCommission(),userNoReCommendId,balance);
            Integer res3=orderService.updateByPrimaryKeySelective(order);
            if(res3<=0){
                bools=false;
                System.out.println("vvv");
                Logger logger= LoggerFactory.getLogger("vvv"+orderNo);
                //throw new RuntimeException();
            }
        }
        return orderbool;
    }
    //查看物流 ----待发货的查看物流
    @RequestMapping("/logistics")
    public  ModelAndView logistics(HttpServletRequest request,String logNo){
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        ModelAndView modelAndView=new ModelAndView("shoppingApi/order/logistics");
        Map<String, Object> map=new HashMap<>();
        logNo="51164633704467";
        Logistics logistics=logisticsService.selectByNo(logNo);
        List<DataInfo> list;
        //JSONArray jsonArray = JSONArray.fromObject(logistics.getLogisticsInfo());//把String转换为json
        list =  JSON.parseArray(logistics.getLogisticsInfo(), DataInfo.class); //.toList(jsonArray,new Person(), new JsonConfig());
        Address address=addressService.selectDefault(1,memberUserId);
        address.setPhone(address.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));//隐藏手机号中间4位
        map.put("logistics",logistics);
        map.put("dataInfo",list);
        map.put("address",address);
        modelAndView.addObject("orderLogistics",map);
        return  modelAndView;
    }

    //发起订阅
    public void subscribe(){
        Config config = configService.selectByPrimaryKey(1);
        String expressCompanyCode = config.getExpressCompanyCode();
        String expressKey = config.getExpressKey();
        String expressApiUrl = config.getExpressApiurl();

        //模拟物流单号数据
        TaskRequest req = new TaskRequest();
        req.setCompany(expressCompanyCode);
        req.setFrom("贵州省贵阳市观山湖区");
        req.setTo("山西太原市小店区");
        req.setNumber("51155868100345");// 快递单号
        req.getParameters().put("callbackurl", "http://100.64.51.0:8092/kuaidi");
        req.setKey(expressKey);

        HashMap<String, String> p = new HashMap<String, String>();
        p.put("schema", "json");
        p.put("param", JacksonHelper.toJSON(req));
        try {
            String ret = HttpRequest.postData(expressApiUrl+"poll", p, "UTF-8");
            TaskResponse resp = JacksonHelper.fromJSON(ret, TaskResponse.class);
            System.out.println(resp.toXml());
            if (resp.getResult() == true) {
                System.out.println("订阅成功");
            } else {
                System.out.println("订阅失败");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
